package com.ctrip.cap.internal.appium.test;

import io.appium.java_client.AppiumDriver;

import java.io.File;
import java.net.URL;

import org.apache.commons.lang3.StringUtils;
import org.openqa.selenium.Capabilities;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.ctrip.cap.AppiumContext;
import com.ctrip.cap.appium.DeviceSwipeDriver;
import com.ctrip.cap.device.Device;
import com.ctrip.cap.device.android.AndroidDevice;
import com.ctrip.cap.internal.appium.suite.AppiumSuiteListener;
import com.ctrip.cap.internal.appium.suite.android.SelendroidBuddy;
import com.ctrip.cap.internal.domain.Context;
import com.ctrip.cap.internal.performance.Profilers;
import com.ctrip.cap.internal.suite.SuiteManListener;
import com.ctrip.cap.internal.suite.SuiteUtility;
import com.ctrip.cap.internal.test.MethodFilter;
import com.ctrip.cap.lanucher.AppiumConfig;
import com.ctrip.cap.lanucher.AppiumServer;

/**
 * @author ltyao
 * @see SuiteManListener for app package path
 */
public class PrepareAppiumDriver implements MethodFilter {
    private static final Logger logger = LoggerFactory
            .getLogger(PrepareAppiumDriver.class);

    @Override
    public void doFilter(Context context2) {

        AppiumContext context = (AppiumContext) context2;
        Device device = (AndroidDevice) context.getDevice();
        AppiumConfig appiumConfig = context.getAppiumConfig();

        appiumConfig.setUdid(device.getSerialNumber()); // very im

        String sourceAppName = appiumConfig.getAppFileName();
        if (StringUtils.isNotBlank(sourceAppName)) {
            File newApp = SuiteUtility.constructFileName(
                    device.getSerialNumber(), sourceAppName);
            appiumConfig.setApp(newApp.getAbsolutePath());
        }


        AppiumServer appiumServer = AppiumSuiteListener.getAppiumServerWithDevice(device);
        context.setAppium(appiumServer);
        if (!appiumServer.isRunning() || appiumConfig.isCaseLevelRestart()) {
            Profilers.preAppium().start("startAppiumServer");
            appiumServer.startAppium();
        }

        URL url = appiumServer.getURL();
        Capabilities capabilities = appiumConfig.toCapabilities();
        logger.info("\nTry connecting to {}", url);
        Profilers.preAppium().start("newWebDriver");

        logger.info("New AppiumDriver may cost 30 seconds or more,have patience ......");
        SelendroidBuddy.sleeping();
        AppiumDriver driver = new DeviceSwipeDriver(url, capabilities, device);
        // driver.manage().timeouts().implicitlyWait(time, unit)
        context.setDriver(driver);

        Profilers.preAppium().stop().log();
    }
}
